package com.xjm.ips.service;

import com.xjm.ips.entity.Hr;
import com.xjm.ips.mapper.HrMapper;
import com.xjm.ips.mapper.HrRoleMapper;
import com.xjm.ips.utils.Hrutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HrService implements UserDetailsService {
    @Autowired
    HrMapper hrMapper;
    @Autowired
    HrRoleMapper hrRoleMapper;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUserName(s);
        if(hr == null){
            throw  new UsernameNotFoundException("用户名不存在!");
        }
        hr.setRoles(hrMapper.getHrRolesById(hr.getId()));
        return  hr;
    }

    public List<Hr> getAllHrs(String keywords) {
        //获取除了自己外其他的用户信息
        return hrMapper.getAllHrs(Hrutils.getCurrentHr().getId(),keywords);
    }

    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        hrRoleMapper.deleteByHrid(hrid);
        return hrRoleMapper.addRole(hrid,rids) == rids.length;
    }

    @Transactional
    public Integer deleteHrById(Integer id) {
        hrRoleMapper.deleteByHrid(id);
        return hrMapper.deleteByPrimaryKey(id);
    }


    public Integer addHr(Hr hr) {
        //密码加密加盐
        String password = new BCryptPasswordEncoder().encode(hr.getPassword());
        hr.setPassword(password);
        hr.setUserface("https://gitee.com/KKP133/personnel_management_system/raw/c55ade806cff382153401a3b4df59686fd6545a6/5.jpg");
        return hrMapper.insertSelective(hr);
    }
}
